// 全局变量
let view = null;

// 初始化ArcGIS地图应用
require([
  "esri/config",
  "esri/Map",
  "esri/views/MapView",
  "esri/layers/FeatureLayer",
  "esri/widgets/Home",
  "esri/widgets/Zoom",
  "esri/widgets/BasemapToggle",
  "esri/widgets/Legend"
], (esriConfig, Map, MapView, FeatureLayer, Home, Zoom, BasemapToggle, Legend) => {

  // 配置 ArcGIS
  esriConfig.request.timeout = 60000;

  // 创建图层 - 配置弹出窗口模板
  const roadsLayer = new FeatureLayer({
    url: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/USA/MapServer/0",
    title: "道路",
    visible: true,
    opacity: 0.8,
    popupTemplate: {
      title: "道路信息",
      content: [
        {
          type: "fields",
          fieldInfos: [
            {
              fieldName: "OBJECTID",
              label: "对象ID",
              visible: true
            },
            {
              fieldName: "NAME",
              label: "道路名称",
              visible: true
            },
            {
              fieldName: "TYPE",
              label: "道路类型",
              visible: true
            },
            {
              fieldName: "SYSTEM",
              label: "道路系统",
              visible: true
            }
          ]
        }
      ],
      actions: [
        {
          title: "查看详情",
          id: "view-details",
          className: "esri-icon-description"
        },
        {
          title: "缩放到要素",
          id: "zoom-to-feature",
          className: "esri-icon-zoom-in-magnifying-glass"
        }
      ]
    }
  });

  const buildingsLayer = new FeatureLayer({
    url: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/USA/MapServer/2",
    title: "建筑物",
    visible: true,
    opacity: 0.7,
    popupTemplate: {
      title: "建筑物信息",
      content: [
        {
          type: "fields",
          fieldInfos: [
            {
              fieldName: "OBJECTID",
              label: "对象ID",
              visible: true
            },
            {
              fieldName: "NAME",
              label: "建筑物名称",
              visible: true
            },
            {
              fieldName: "TYPE",
              label: "建筑物类型",
              visible: true
            },
            {
              fieldName: "ADDRESS",
              label: "地址",
              visible: true
            }
          ]
        },
        {
          type: "text",
          text: "<p><strong>位置信息：</strong>该建筑物位于城市中心区域。</p>"
        }
      ],
      actions: [
        {
          title: "查看详情",
          id: "view-details",
          className: "esri-icon-description"
        },
        {
          title: "缩放到要素",
          id: "zoom-to-feature",
          className: "esri-icon-zoom-in-magnifying-glass"
        }
      ]
    }
  });

  const parksLayer = new FeatureLayer({
    url: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/USA/MapServer/1",
    title: "公园绿地",
    visible: false,
    opacity: 0.9,
    popupTemplate: {
      title: "公园绿地信息",
      content: [
        {
          type: "fields",
          fieldInfos: [
            {
              fieldName: "OBJECTID",
              label: "对象ID",
              visible: true
            },
            {
              fieldName: "NAME",
              label: "公园名称",
              visible: true
            },
            {
              fieldName: "TYPE",
              label: "绿地类型",
              visible: true
            },
            {
              fieldName: "AREA",
              label: "面积",
              visible: true
            }
          ]
        },
        {
          type: "media",
          mediaInfos: [
            {
              title: "公园概览",
              type: "image",
              value: {
                sourceURL: "https://via.placeholder.com/300x200/90EE90/000000?text=公园绿地"
              }
            }
          ]
        }
      ],
      actions: [
        {
          title: "查看详情",
          id: "view-details",
          className: "esri-icon-description"
        },
        {
          title: "缩放到要素",
          id: "zoom-to-feature",
          className: "esri-icon-zoom-in-magnifying-glass"
        }
      ]
    }
  });

  // 创建地图
  const map = new Map({
    basemap: "streets-vector",
    layers: [roadsLayer, buildingsLayer, parksLayer]
  });

  // 创建视图
  view = new MapView({
    container: "viewDiv",
    map: map,
    center: [-98, 39],
    zoom: 4,
    constraints: {
      minZoom: 2,
      maxZoom: 18
    }
  });

  // 添加地图控件
  const homeBtn = new Home({ view: view });

  // 创建图例组件
  const legend = new Legend({
    view: view,
    style: "classic"
  });

  view.ui.add(homeBtn, "top-left");
  view.ui.add(legend, "bottom-right");

  // 视图加载完成
  view.when(() => {
    console.log("地图加载完成");
  });

  // 绑定图层控制开关
  document.getElementById("roads-switch").addEventListener("calciteSwitchChange", (e) => {
    roadsLayer.visible = e.target.checked;
  });

  document.getElementById("buildings-switch").addEventListener("calciteSwitchChange", (e) => {
    buildingsLayer.visible = e.target.checked;
  });

  document.getElementById("parks-switch").addEventListener("calciteSwitchChange", (e) => {
    parksLayer.visible = e.target.checked;
  });

  // 主题切换
  const themeSelect = document.getElementById("theme-select");
  themeSelect.addEventListener("calciteSelectChange", (e) => {
    const theme = e.target.value;
    document.documentElement.setAttribute("data-theme", theme);

    // 根据主题调整地图底图
    switch (theme) {
      case "dark":
        map.basemap = "dark-gray-vector";
        break;
      case "blue":
        map.basemap = "oceans";
        break;
      case "green":
        map.basemap = "terrain";
        break;
      default:
        map.basemap = "streets-vector";
    }
  });

  // 底图选择
  const basemapSelect = document.getElementById("basemap-select");
  basemapSelect.addEventListener("calciteSelectChange", (e) => {
    const selectedBasemap = e.target.value;

    // 切换ArcGIS免费底图
    map.basemap = selectedBasemap;
    console.log("切换到底图:", selectedBasemap);
  });

  // 错误处理
  view.on("layerview-create-error", (event) => {
    console.error("图层加载错误:", event.error);
  });

  // 配置弹出窗口动作处理
  view.popup.on("trigger-action", (event) => {
    const actionId = event.action.id;
    const selectedFeature = view.popup.selectedFeature;

    if (actionId === "view-details") {
      // 查看详情动作
      console.log("查看详情:", selectedFeature.attributes);
      alert(`查看详情：\n对象ID: ${selectedFeature.attributes.OBJECTID}\n名称: ${selectedFeature.attributes.NAME || '未命名'}`);
    } else if (actionId === "zoom-to-feature") {
      // 缩放到要素动作
      const geometry = selectedFeature.geometry;
      if (geometry) {
        view.goTo({
          target: geometry,
          zoom: view.zoom + 2 // 放大2级
        }).then(() => {
          console.log("已缩放到要素");
        }).catch((error) => {
          console.error("缩放失败:", error);
        });
      }
    }
  });

  // 添加点击事件监听器（可选，用于自定义处理）
  view.on("click", (event) => {
    // 检查是否点击了要素
    view.hitTest(event).then((response) => {
      if (response.results.length > 0) {
        const graphic = response.results[0].graphic;
        console.log("点击了要素:", graphic.attributes);
      }
    });
  });
});

// 左侧面板折叠/展开功能
function togglePanel() {
  const panel = document.getElementById('leftPanel');
  const isCollapsed = panel.classList.contains('collapsed');

  if (isCollapsed) {
    // 展开面板
    panel.classList.remove('collapsed');
    console.log("左侧面板已展开");
  } else {
    // 折叠面板
    panel.classList.add('collapsed');
    console.log("左侧面板已折叠");
  }

  // 保存状态到localStorage
  savePanelState();
}

// 从localStorage恢复面板状态
window.addEventListener('load', function() {
  const panelState = localStorage.getItem('leftPanelCollapsed');
  const panel = document.getElementById('leftPanel');

  if (panelState === 'true') {
    panel.classList.add('collapsed');
  }
});

// 保存面板状态到localStorage
function savePanelState() {
  const panel = document.getElementById('leftPanel');
  const isCollapsed = panel.classList.contains('collapsed');
  localStorage.setItem('leftPanelCollapsed', isCollapsed);
}

console.log("Calcite Design System 地图示例加载完成");
